package com.tengju.data.infrastructure.schedule;

import com.tengju.data.application.sync.ActivitySyncApplicationService;
import com.tengju.data.domain.model.alert.AlertEvent;
import com.tengju.data.domain.model.alert.AlertService;
import com.tengju.data.domain.shared.CastUtil;
import com.tengju.motivation.domain.model.activity.Activity;
import com.tengju.motivation.domain.model.activity.ActivityId;
import com.tengju.motivation.domain.model.activity.ActivityRepository;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenhang
 * @Date 2022/1/8
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ActivityCrowdSyncJob {

    private final AlertService alertService;
    private final ActivitySyncApplicationService activitySyncApplicationService;
    private final ActivityRepository activityRepository;

    private final String jobName = "活动意向人群同步任务";

    @XxlJob("activityCrowdSyncJob")
    public ReturnT<String> execute(String params) {
        try {
            if (!StringUtils.isBlank(params)) {
                Long activityId = CastUtil.castLong(params);
                Activity activity = activityRepository.getActivityById(new ActivityId(activityId));
                activitySyncApplicationService.syncActivityCrowd(activity);
                return ReturnT.SUCCESS;
            }
            LocalDateTime now = LocalDateTime.now();
            LocalDate activityEndDate = now.toLocalDate();
            if (now.getHour() < 1) {
                activityEndDate = now.toLocalDate().minusDays(1);
            }
            List<Long> activityIds = activityRepository.listNoEndActivityIds(activityEndDate);
            if (CollectionUtils.isEmpty(activityIds)) {
                log.info("没有活动需要同步人群");
                return ReturnT.SUCCESS;
            }
            for (Long activityId : activityIds) {
                log.info("活动人群同步 开始活动：{} ",activityId);
                Activity activity = activityRepository.getActivityById(new ActivityId(activityId));
                activitySyncApplicationService.syncActivityCrowd(activity);
                log.info("活动人群同步 结束活动：{} ",activityId);
            }
        } catch (Exception e) {
            log.error("{}, jobError",jobName, e);
            AlertEvent event = new AlertEvent(jobName + "异常");
            event.addItem("任务参数",params);
            event.addItem("异常信息",e.getMessage());
            alertService.alert(event);
        }
        return ReturnT.SUCCESS;
    }




}
